<template>
  <div class="app-container">
    <el-form ref="noticedemandapprovalRef" :model="formData" :rules="rules" label-width="140px">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="立案号" prop="caseId">
            <el-select
              v-model="formData.caseId"
              placeholder="请选择立案号"
              :disabled="disabled || isFlow"
              clearable
              @change="handleCase">
              <el-option v-for="item in numberList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="当事人名称" prop="partyName">
            <el-input v-model="formData.partyName" disabled placeholder="请输入当事人名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="案件名称" prop="caseName">
            <el-input v-model="formData.caseName" disabled placeholder="请输入案件名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="送审材料接收时间" prop="receivedTime">
            <el-date-picker
              clearable
              v-model="formData.receivedTime"
              :disabled="disabled || isFlow"
              type="date"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择送审材料接收时间"
              style="width: 100%"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <div class="form-title-text-two" style="margin-bottom: 20px">法制机构意见</div>
        </el-col>
        <template v-for="item in opinionList" :key="item.value">
          <el-col :span="24">
            <el-form-item :label="item.label" :prop="item.field" class="long-label">
              <el-radio-group v-model="formData[item.field]" :disabled="disabled || isFlow">
                <el-radio v-for="itemx in isPassList" :value="itemx.value">
                  {{ itemx.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="" class="long-label">
              <el-input
                v-model="formData[item.field2]"
                type="textarea"
                :rows="3"
                :disabled="disabled || isFlow"
                placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
        </template>
        <el-col :span="24">
          <el-form-item label="其他应审核的内容" prop="otherAuditProbSugges">
            <el-input
              v-model="formData.otherAuditProbSugges"
              type="textarea"
              :rows="3"
              :disabled="disabled || isFlow"
              placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="审核人员意见" prop="handlerOpinion">
            <el-input
              v-model="formData.handlerOpinion"
              :disabled="disabled || isFlow"
              type="textarea"
              :rows="3"
              placeholder="请输入审核人员意见" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="formData.remark"
              :disabled="disabled"
              type="textarea"
              :rows="3"
              placeholder="请输入备注" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance, watch, onBeforeUnmount } from 'vue'
import {
  getLegalReviewOpinion,
  addLegalReviewOpinion,
  updateLegalReviewOpinion,
  getCaseList,
  submitLegalReviewOpinion,
  reviewLegalReviewOpinion,
  getContent,
  previewPdf,
} from '@/api/caseHandling/legalReview.js'
import { registrationcaseDetail } from '@/api/filingReview/register'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const { proxy } = getCurrentInstance()

// Props
const props = defineProps({
  id: {
    type: [String, Number],
    default: null,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  isFlow: {
    type: Boolean,
    default: false,
  },
})

const router = useRouter()

// Emits
const emit = defineEmits(['handleSubmit'])

// Form data
const formData = ref({
  id: null,
  caseId: null,
  caseNo: null,
  partyName: null,
  caseName: null,
  receivedTime: null,
  handlerOpinion: null,
  remark: null,
})
// Form validation rules
const rules = {
  caseNo: [{ required: true, message: '立案号不能为空', trigger: ['blur', 'change'] }],
  partyName: [{ required: true, message: '当事人名称不能为空', trigger: ['blur', 'change'] }],
  caseName: [{ required: true, message: '案件名称不能为空', trigger: ['blur', 'change'] }],
  receivedTime: [{ required: true, message: '送审材料接收时间不能为空', trigger: ['blur', 'change'] }],
  caseId: [{ required: true, message: '立案号不能为空', trigger: ['blur', 'change'] }],
  handlerOpinion: [{ required: true, message: '审核人员意见不能为空', trigger: ['blur', 'change'] }],
  caseMaterialsComplete: [{ required: true, message: '请选择', trigger: ['blur', 'change'] }],
  lawEnforcementSubjectValid: [{ required: true, message: '请选择', trigger: ['blur', 'change'] }],
  enforcerQualified: [{ required: true, message: '请选择', trigger: ['blur', 'change'] }],
  partyIdentifiedAccurate: [{ required: true, message: '请选择', trigger: ['blur', 'change'] }],
  factsEvidenceValid: [{ required: true, message: '请选择', trigger: ['blur', 'change'] }],
  lawEnforcementProcedureLegal: [{ required: true, message: '请选择', trigger: ['blur', 'change'] }],
  lawsAppliedCorrect: [{ required: true, message: '请选择', trigger: ['blur', 'change'] }],
  handlingSuggestionAppropriate: [{ required: true, message: '请选择', trigger: ['blur', 'change'] }],
  suspectedCrimeTransfer: [{ required: true, message: '请选择', trigger: ['blur', 'change'] }],
  otherAuditProbSugges: [{ required: true, message: '请输入其他应审核的内容', trigger: ['blur', 'change'] }],
}
const isPassList = [
  { label: '通过', value: '1' },
  { label: '不通过', value: '2' },
]
const opinionList = ref([
  {
    value: '0',
    label: '案件材料是否完整、文书是否完备、制作是否规范',
    field: 'caseMaterialsComplete',
    field2: 'caseMaterialsCompleteProbSugges',
  },
  {
    value: '1',
    label: '执法主体、执法权限是否合法',
    field: 'lawEnforcementSubjectValid',
    field2: 'lawEnforcementSubjectValidProbSugges',
  },
  { value: '2', label: '执法人员是否具备执法资格', field: 'enforcerQualified', field2: 'enforcerQualifiedProbSugges' },
  {
    value: '3',
    label: '当事人是否认定准确',
    field: 'partyIdentifiedAccurate',
    field2: 'partyIdentifiedAccurateProbSugges',
  },
  {
    value: '4',
    label: '事实是否清楚，证据是否来源合法、查证属实且对相关事实具有充分的证明效力，查证情况是否记录完整、准确',
    field: 'factsEvidenceValid',
    field2: 'factsEvidenceValidProbSugges',
  },
  {
    value: '5',
    label: '执法程序是否合法',
    field: 'lawEnforcementProcedureLegal',
    field2: 'lawEnforcementProcedureLegalProbSugges',
  },
  {
    value: '6',
    label: '法律、法规、规章是否适用正确',
    field: 'lawsAppliedCorrect',
    field2: 'lawsAppliedCorrectProbSugges',
  },
  {
    value: '7',
    label: '办案机构的办理建议和裁量建议是否明确、适当',
    field: 'handlingSuggestionAppropriate',
    field2: 'handlingSuggestionAppropriateProbSugges',
  },
  {
    value: '8',
    label: '违法行为是否涉嫌犯罪或者职务违法，是否需要移送公安机关或者监察机关',
    field: 'suspectedCrimeTransfer',
    field2: 'suspectedCrimeTransferSugges',
  },
])

// Refs
const noticedemandapprovalRef = ref()

// Methods
const reset = () => {
  formData.value = {
    id: null,
    caseId: null,
    caseNo: null,
    partyName: null,
    caseName: null,
    receivedTime: null,
    handlerOpinion: null,
    remark: null,
  }
  proxy.resetForm('noticedemandapprovalRef')
}

// Get detail data
const getDetail = async id => {
  reset()
  if (id) {
    try {
      const res = await getLegalReviewOpinion(id)
      if (!res?.data) return
      formData.value = res.data
    } catch (error) {
      console.error('获取详情失败:', error)
    }
  }
}

const handleCase = async val => {
  return new Promise(async (resolve, reject) => {
    if (!val) {
      formData.value.caseNo = ''
      formData.value.partyName = ''
      formData.value.caseName = ''
      formData.value.receivedTime = ''
      formData.value.partyId = ''
      return
    }
    const res = await registrationcaseDetail(val)
    const { partyName, partyId } = res.data
    formData.value.caseNo = res.data.caseNo
    formData.value.partyName = partyName
    formData.value.partyId = partyId
    const res2 = await getContent(val)
    formData.value.handlerOpinion = res2.data.handlerOpinion
    formData.value.caseName = res2.data.caseName
    formData.value.receivedTime = res2.data.receivedTime
    resolve()
  })
}

const handlePreview = () => {
  return new Promise(resolve => {
    submitForm(false, true)
      .then(async params => {
        previewPdf(params)
          .then(res => {
            if (!!res.msg) {
              window.open(res.msg)
              resolve()
            } else {
              ElMessage.warning('预览文件不存在')
              resolve()
            }
          })
          .catch(() => {
            ElMessage.warning('预览文件不存在')
            resolve()
          })
      })
      .catch(() => {
        ElMessage.warning('请先完善表单信息')
        resolve()
      })
  })
}

// Submit form
const caseSituationRef = ref(null)
const submitForm = (isDraft = false, isPreview = false) => {
  return new Promise((resolve, reject) => {
    noticedemandapprovalRef.value
      .validate()
      .then(async () => {
        if (isPreview === true) {
          // 预览不提交
          resolve({ ...formData.value })
          return
        }
        let result
        if (isDraft) {
          // 草稿
          if (formData.value.id) {
            result = await updateLegalReviewOpinion(formData.value)
          } else {
            result = await addLegalReviewOpinion(formData.value)
          }
        } else {
          // 提交
          result = await submitLegalReviewOpinion(formData.value)
        }

        ElMessage.success(isDraft ? '保存草稿成功' : '提交成功')
        emit('handleSubmit', result)
        return result
      })
      .catch(error => {
        console.error('表单验证失败:', error)
        reject(error)
      })
  })
}

// 待办页面 提交 / 退回
const handleSubmitReview = async form => {
  await reviewLegalReviewOpinion({
    ...form,
    id: props.editId || props.id,
  })
  proxy.$modal.msgSuccess('操作成功')
  router.back()
}

// 待办页面获取批注列表
const timer = ref(null)
const getAnnotationList = () => {
  return new Promise((resolve, reject) => {
    timer.value = setInterval(() => {
      if (formData.value.id) {
        clearInterval(timer.value)
        resolve({ ...formData.value })
      } else {
        resolve([])
      }
    }, 500)
  })
}

// Watch props.id change
watch(
  () => props.id,
  newVal => {
    if (newVal) {
      getDetail(newVal)
    } else {
      reset()
    }
    handleCaseList()
  },
  { immediate: true }
)

const numberList = ref([])
async function handleCaseList() {
  const res = await getCaseList()
  numberList.value = res.data.map(item => ({
    label: item.caseNo,
    value: item.id,
  }))
}
onBeforeUnmount(() => {
  if (timer.value) {
    clearInterval(timer.value)
  }
})
// Expose methods
defineExpose({
  submitForm,
  handlePreview,
  reset,
  formData,
  getAnnotationList,
  handleSubmitReview,
  formRef: noticedemandapprovalRef,
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}
</style>
